package com.alex.DAO;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.alex.entity.Administrator;
import com.alex.entity.User;

public class AdminDAO extends BaseDAO implements IAdminDAO {
	public void saveAdmin(Administrator admin){
		Session session=getSession();
		Transaction tx=session.beginTransaction();
		
		System.out.println(admin.getUsername());
		
		session.save(admin);
		tx.commit();
		session.close();
	}
	public Administrator validateAdmin(String username,String password){
		Session session=getSession();
		String hql="from Administrator u where u.username=? and u.password=?";
		Query query=session.createQuery(hql);
		query.setParameter(0,username);
		query.setParameter(1, password);
		List admins=query.list();
		if(admins.size()!=0){
			Administrator admin=(Administrator)admins.get(0);
			return admin;
		}
		session.close();
		return null;
	}
	public void deleteUser(List Users){
		Transaction tx=null;
		try{
		Session session=getSession();
		 tx=session.getTransaction();
		session.beginTransaction();
		Query query =session.createQuery("delete User u where u.id=?");
		Users=query.list();
		if(Users.size()!=0){
			int i=0;
			while(i<Users.size()){
			User u=(User)Users.get(i);
			query.executeUpdate();
			i++;
			}
		}
		
		tx.commit();
		}
			catch(HibernateException e){
				tx.rollback();
				e.printStackTrace();
			}
	}
	public List showUser(){
		Session session=getSession();
		Query query=session.createQuery("select u from User u");
		List Users=query.list();
		session.close();
		return Users;
	}
	public List QueryUser(String User){
		Session session=getSession();
		Query query=session.createQuery("from User u where u.username like '%'+User+'%'");
		List Users=query.list();
		session.close();
		return Users;
	}
}
